﻿using FileSynchronizationClient.Common;
using FileSynchronizationClient.Models;
using Newtonsoft.Json;

namespace FileSynchronizationClient.Service
{

    public class UserService
    {
        private static string templateBasePath = "C:\\ProgramData\\FileSynchronization";

        private string templateFilePath = Path.Combine(templateBasePath, "userSetting.txt");

        private UserHttpClient _client;

        private SettingMaps _settingMaps;

        public UserService(
            UserHttpClient userHttpClient,
            SettingMaps settingMaps)
        {
            _client = userHttpClient;
            _settingMaps = settingMaps;
        }

        /// <summary>
        /// 获取用户Token
        /// </summary>
        /// <returns></returns>
        /// <exception cref="Exception"></exception>
        public async Task<(int, string)> Login()
        {
            // 检查是否存在 Template 文件
            bool templateExists = File.Exists(templateFilePath);

            UserModel userModel;

            if (templateExists)
                // 如果存在 Template 文件，从文件中读取用户信息
                userModel = ReadUserModelFromFile(templateFilePath);
            else
                // 从控制台输入获取用户信息
                userModel = GetUserModelFromConsole();

            // 获取对应的文件信息
#if DEBUG
            var basePath = @"D:\work\Wechat_PublicNumber";
#else
                var basePath = AppDomain.CurrentDomain.BaseDirectory;
#endif

            int Type = 0;

            foreach (var map in _settingMaps.List)
            {
                var filePath = Path.Combine(basePath, map.UniqueFileName);
                if (File.Exists(filePath))
                {
                    Type = map.Type;
                    break;
                }
            }

            if (Type == 0)
                throw new Exception("当前项目类型暂未开发，请联系管理员处理！");

            // 调用 User 服务获取Token
            var token = await GetToken(new GetTokenRequest()
            {
                Type = Type,
                UserName = userModel.UserName,
                PassWord = userModel.PassWord
            });

            if (string.IsNullOrEmpty(token))
                throw new Exception("用户权限校验失败，请联系管理员处理！");

            // 将用户信息序列化并存储到 Template 文件中
            SaveUserModelToFile(userModel);

            return (Type, token);
        }

        /// <summary>
        /// 读取用户配置文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static UserModel ReadUserModelFromFile(string filePath)
        {
            string templateContent = File.ReadAllText(filePath);
            return JsonConvert.DeserializeObject<UserModel>(templateContent);
        }

        /// <summary>
        /// 从Console中获取用户配置
        /// </summary>
        /// <returns></returns>
        private static UserModel GetUserModelFromConsole()
        {
            Console.Write("请输入账号：");
            string account = Console.ReadLine();

            Console.Write("请输入密码：");
            string password = Console.ReadLine();

            return new UserModel
            {
                UserName = account,
                PassWord = password
            };
        }

        /// <summary>
        /// GetToken
        /// </summary>
        /// <param name="userModel"></param>
        /// <returns></returns>
        private async Task<string> GetToken(GetTokenRequest request)
        {
            // 调用 User 服务进行权限校验
            var respones = await _client.GetToken(request);

            if (respones.Code != 200)
                throw new Exception(respones.Error.ToString());

            return respones.Data.ToString();
        }

        /// <summary>
        /// 保存用户配置文件
        /// </summary>
        /// <param name="userModel"></param>
        /// <param name="fileName"></param>
        private void SaveUserModelToFile(UserModel userModel)
        {
            if (!Directory.Exists(templateBasePath))
                Directory.CreateDirectory(templateBasePath);

            if (File.Exists(templateFilePath)) File.Delete(templateFilePath);

            string userModelJson = JsonConvert.SerializeObject(userModel);
            File.WriteAllText(templateFilePath, userModelJson);
            File.SetAttributes(templateFilePath, File.GetAttributes(templateFilePath) | FileAttributes.Hidden);
        }
    }
}
